//
//  BBuyNowShopDetailVC.m
//  DistributorAB
//
//  Created by LZY on 2019/10/9.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "BBuyNowShopDetailVC.h"
#import "BBuyNowShopDetailNavView.h"//导航栏
#import "BBuyNowShopDetailImageCycleView.h"//轮播图
#import "BBuyNowShopDetailContentCell.h"//购买cell
#import "BBuyNowShopDetailStoreCell.h"//店铺cell
#import "BBuyNowShopDetailWebCell.h"//图文详情
#import "BBuyNowShopDetailBottomView.h"//底部按钮
#import "BBuyNowAddPartSuccessView.h"//添加成功提示

#import "BShopPartDetailModel.h"

#import "BBuyNowShopStoreVC.h"//店铺
#import "ZYHouBaoOrderFormViewController.h"

@interface BBuyNowShopDetailVC () <UITableViewDelegate,UITableViewDataSource,BBuyNowShopDetailNavViewDelegate,BBuyNowShopDetailImageCycleViewDelegate,BBuyNowShopDetailImageCycleViewDataSource,BBuyNowShopDetailContentCellDelegate,BBuyNowShopDetailStoreCellDelegate,BBuyNowShopDetailWebCellDelegate,BBuyNowShopDetailBottomViewDelegate>
{
    BOOL _isClickNav;//是否是点击的导航栏
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) BBuyNowShopDetailNavView *viewNav;
@property (nonatomic, strong) BBuyNowShopDetailImageCycleView *viewCycleBanner;

@property (nonatomic, strong) BBuyNowShopDetailContentCell *contentCell;
@property (nonatomic, strong) BBuyNowShopDetailWebCell *webCell;
@property (nonatomic, strong) BShopPartDetailModel *shopModel;
@property (nonatomic, strong) BShopPartTypeModel *selectedTypeModel;//选中的型号
@property (nonatomic, assign) BOOL isSubmit;//是否在提交数据
@end

@implementation BBuyNowShopDetailVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupNavViewAction];
    
    [self setupViewAction];
    [self requestData];
}
#pragma mark - 导航栏布局
- (void)setupNavViewAction{
    _viewNav = [[BBuyNowShopDetailNavView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kNaviHeight)];
    _viewNav.delegate = self;
    [self.view addSubview:_viewNav];
    
}
#pragma mark - 界面布局
- (void)setupViewAction{
    
    BBuyNowShopDetailBottomView *viewBottom = [[BBuyNowShopDetailBottomView alloc] initWithFrame:CGRectMake(0, kScreen_Height - 43 - TabbarSafeBottomMargin, kScreen_Width, 43 + TabbarSafeBottomMargin)];
    viewBottom.delegate = self;
    [self.view addSubview:viewBottom];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight, kScreen_Width, kScreen_Height - kNaviHeight - viewBottom.height) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
//    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[BBuyNowShopDetailContentCell class] forCellReuseIdentifier:NSStringFromClass([BBuyNowShopDetailContentCell class])];
    [_tableView registerClass:[BBuyNowShopDetailStoreCell class] forCellReuseIdentifier:NSStringFromClass([BBuyNowShopDetailStoreCell class])];
    [_tableView registerClass:[BBuyNowShopDetailWebCell class] forCellReuseIdentifier:NSStringFromClass([BBuyNowShopDetailWebCell class])];
    
    _viewCycleBanner = [[BBuyNowShopDetailImageCycleView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Width) withTimerValue:3.0];
    _viewCycleBanner.delegate = self;
    _viewCycleBanner.dataSource = self;
    _tableView.tableHeaderView = _viewCycleBanner;
}
#pragma mark - 数据请求
- (void)requestData{
    [MBProgressHUD showHUDAddedTo:self.view msg:@"数据加载中" animated:YES];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObjectIfNotNil:self.shopID forKey:@"id"];
    [param setObjectIfNotNil:@"2" forKey:@"user_type"];//2所有经销商1维修工
    kWeakSelf;
    [NetWorkTool POST:getPartsInfo param:param success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.shopModel = [BShopPartDetailModel mj_objectWithKeyValues:[dic objectForKeyNotNil:@"data"]];
        [weakSelf.tableView reloadData];
        [weakSelf.viewCycleBanner reloadData];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } needUser:YES];
}
#pragma mark - BBuyNowShopDetailNavViewDelegate
- (void)navViewBtnClick:(NSInteger)tag{
    if (tag == 202) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if (tag == 201){
        //详情
        _isClickNav = YES;
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }else if (tag == 200){
        //产品
        _isClickNav = YES;
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    }else if (tag == 203){
        //预订车
        ZYHouBaoOrderFormViewController *vc = [ZYHouBaoOrderFormViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        if (!self.shopModel) {
            return [UITableViewCell new];
        }
        BBuyNowShopDetailContentCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BBuyNowShopDetailContentCell class]) forIndexPath:indexPath];
        cell.delegate = self;
        self.contentCell = cell;
        cell.partModel = self.shopModel;
        return cell;
    }
//    else if (indexPath.row == 1){
//        BBuyNowShopDetailStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BBuyNowShopDetailStoreCell class]) forIndexPath:indexPath];
//        cell.partModel = self.shopModel;
//        cell.delegate = self;
//        return cell;
//    }
    else if (indexPath.row == 1){
        BBuyNowShopDetailWebCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BBuyNowShopDetailWebCell class]) forIndexPath:indexPath];
        cell.partID = self.shopID;
        cell.delegate = self;
        self.webCell = cell;
        return cell;
    }
    return [UITableViewCell new];
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        if (self.shopModel) {
            return [self.contentCell cellHeight];
        }else{
            return 0;
        }
    }
    else if (indexPath.row == 1){
        return self.webCell.cellHeight;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 1) {
//        BBuyNowShopStoreVC *vc = [BBuyNowShopStoreVC new];
//        vc.storeID = self.shopModel.factory.Id;
//        vc.storeModel = self.shopModel;
//        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //解决点击事件和滑动事件的冲突
    if (_isClickNav) {
        return;
    }
    
    //获得可视范围内的第一个cell
    UITableViewCell *cell = [self.tableView visibleCells].firstObject;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row >= 1) {
        //nav选中 详情
        [self.viewNav btnClickAction:self.viewNav.btnRight];
    }else{
        //nav选中 产品
        [self.viewNav btnClickAction:self.viewNav.btnLeft];
    }
}
//停止滚动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    _isClickNav = NO;
}

#pragma mark - BBuyNowShopDetailImageCycleViewDataSource - 轮播图
- (NSInteger)numberOfImagesForView:(BBuyNowShopDetailImageCycleView *)cycleView{
    return self.shopModel.lbImg.count;
}
//轮播图填充
- (UIView *)cycleView:(BBuyNowShopDetailImageCycleView *)cycleView imageAtIndex:(NSInteger)index{
    UIImageView *ivCycle = [[UIImageView alloc] initWithFrame:cycleView.bounds];
    ivCycle.contentMode = UIViewContentModeScaleToFill;
    BShopPartCycleModel *model = [self.shopModel.lbImg objectAtIndexSafe:index];
    [HFTools imageViewUpdateWithUrl:model.image_url withImageView:ivCycle withPlaceholderImage:@""];
    return ivCycle;
}
#pragma mark - BBuyNowShopDetailImageCycleViewDelegate
- (void)cycleView:(BBuyNowShopDetailImageCycleView *)cycleView didSelectedAtIndex:(NSInteger)index{
    KMyLog(@"点击了轮播图%ld",(long)index);
}
#pragma mark - BBuyNowShopDetailContentCellDelegate
- (void)buyNowShopDetailContentCellBtnArrowClick{
  
    [_tableView reloadData];
}
- (void)buyNowShopDetailContentCellSelectedType:(BShopPartTypeModel *)typeModel{
    self.selectedTypeModel = typeModel;
    [_tableView reloadData];
}
#pragma mark - BBuyNowShopDetailStoreCellDelegate
- (void)shopDetailStoreCellClickPart:(NSString *)partID{
    BBuyNowShopDetailVC *vc = [BBuyNowShopDetailVC new];
    vc.shopID = partID;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - BBuyNowShopDetailWebCellDelegate
- (void)buyNowShopDetailWebCellReload:(CGFloat)cellHeight{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
#pragma mark - BBuyNowShopDetailBottomViewDelegate
- (void)detailBottomViewClick:(NSInteger)tag{
    if (tag == 200) {
        //咨询电话
        NSString *telephoneNumber = self.shopModel.contactPhone;
        if (telephoneNumber.length > 0) {
            NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@",telephoneNumber];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }
    }else if (tag == 201){
        //加入购物车
        KMyLog(@"self.selectedTypeModel.Id %@", self.selectedTypeModel.Id);

        if (self.shopModel && self.selectedTypeModel) {
            if (_isSubmit) {
                return;
            }
            kWeakSelf;
            _isSubmit = YES;
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:self.shopID forKey:@"id"];//配件ID
            [dict setObjectIfNotNil:self.selectedTypeModel.Id forKey:@"attribute"];//类型ID
            [dict setObjectIfNotNil:@(self.shopModel.buyNumber) forKey:@"count"];//个数
            [dict setObject:@"2" forKey:@"user_type"];//经销商
            KMyLog(@"输出一下上传的参数 %@", dict);

            [NetWorkTool POST:partAddOrder param:dict success:^(id dic) {
                weakSelf.isSubmit = NO;
                BBuyNowAddPartSuccessView *viewAlert = [[BBuyNowAddPartSuccessView alloc] init];
                //viewAlert.delegate = self;
                [viewAlert showView];
                [[NSNotificationCenter defaultCenter] postNotificationName:USER_ADD_ORDER_SUCCESS object:nil];
            } other:^(id dic) {
                weakSelf.isSubmit = NO;
                ShowToastWithText(dic[@"msg"]);
            } fail:^(NSError *error) {
                weakSelf.isSubmit = NO;
                ShowToastWithText(@"加入预订失败，请稍后再试");
            } needUser:YES];
            
        }else{
            ShowToastWithText(@"请选择型号");
        }
    }
}


@end
